<template>
  <div class="pdf-container"
       @dragover.prevent
       @drop.prevent="handleFileDrop"
       @dragenter.prevent="isDraggingOver = true"
       @dragleave.prevent="handleDragLeave">
    <!-- PDF预览区域 -->
    <div v-if="showPreview"
         class="preview-wrapper"
         :class="{ 'drag-over-highlight': isDraggingOver }">
      <div class="preview-content">
        <!-- 左侧缩略图栏 -->
        <div class="thumbnail-sidebar">
          <div class="thumbnail-list" ref="thumbnailList" @scroll="handleThumbnailScroll">
            <div v-for="(page, index) in pages"
                 :key="`page-${page.index}-${page.url}`"
                 class="thumbnail-item"
                 :class="{
                   active: currentPage === index + 1,
                   'drag-over': draggedOverItem === index,
                   'processing': page.status === 'processing',
                   'error': page.status === 'error',
                   'rotated': hasRotation(index)
                 }"
                 @click="goToPage(index + 1)"
                 draggable="true"
                 @dragstart="handleDragStart($event, index)"
                 @dragover.prevent
                 @dragenter="handleDragEnter($event, index)"
                 @dragleave="handleDragLeave($event, index)"
                 @drop="handleDrop($event, index)">
              <div class="thumbnail-wrapper">
                <!-- 处理中状态 -->
                <div v-if="page.status === 'processing'" class="processing-placeholder">
                  <div class="processing-content">
                    <div class="processing-spinner"></div>
                    <div class="processing-text">处理中...</div>
                  </div>
                </div>
                <!-- 错误状态 -->
                <div v-else-if="page.status === 'error'" class="error-placeholder">
                  <div class="error-content">
                    <div class="error-icon">⚠️</div>
                    <div class="error-text">加载失败</div>
                    <button class="retry-btn" @click.stop="retryLoadPage(index)">重试</button>
                  </div>
                </div>
                <!-- 正常图片 -->
                <img
                    v-else-if="page.status === 'loaded' && shouldLoadThumbnail(index)"
                    :src="getThumbnailUrl(page, index)"
                    class="thumbnail-image"
                    :style="{ transform: `rotate(${pageRotations[index] || 0}deg)` }"
                    alt="Page thumbnail"
                    @error="handleImageError($event, index)"
                    @load="handleThumbnailLoad(index)"
                />
                <!-- 懒加载占位符 -->
                <div v-else class="lazy-placeholder">
                  <div class="lazy-content">
                    <div class="lazy-icon">📄</div>
                    <div class="lazy-text">第{{ index + 1 }}页</div>
                  </div>
                </div>
                <!-- 旋转标识 -->
                <div v-if="hasRotation(index)" class="rotation-indicator">
                  <span class="rotation-badge">已旋转</span>
                </div>
                <button
                    class="delete-btn"
                    @click.stop="deletePage(index)"
                    v-if="page.status === 'loaded'"
                >
                  删除
                </button>
              </div>
            </div>
          </div>
          <div class="upload-actions">
            <button class="add-page-btn" @click="triggerFileInput">
              添加页面
            </button>
            <input
                type="file"
                ref="fileInput"
                @change="handleFileChange"
                style="display: none;"
                accept=".pdf,.jpg,.jpeg,.png"
            />
          </div>
        </div>
        <!-- 右侧主预览区域 -->
        <div class="preview-main">
          <!-- 工具栏 -->
          <div class="toolbar">
            <div class="toolbar-left">
              <button @click="prevPage"
                      :disabled="currentPage <= 1"
                      class="btn-tool">
                &lt;
              </button>
              <span class="page-info">
                第 {{ currentPage }} 页 / 共 {{ totalPages }} 页
                <span v-if="processingPages > 0" class="processing-info">
                  ({{ processingPages }} 页处理中)
                </span>
                <span v-if="hasUnsavedRotations" class="unsaved-info">
                  (有未保存的旋转)
                </span>
              </span>
              <button @click="nextPage"
                      :disabled="currentPage >= totalPages"
                      class="btn-tool">
                &gt;
              </button>
            </div>
            <div class="toolbar-right">
              <button @click="zoomOut" class="btn-tool">
                -
              </button>
              <span class="zoom-info">{{ Math.round(scale * 100) }}%</span>
              <button @click="zoomIn" class="btn-tool">
                +
              </button>
              <button @click="rotateCurrentPage"
                      :disabled="currentPageStatus !== 'loaded'"
                      class="btn-tool"
                      :class="{ 'has-rotation': hasCurrentPageRotation }">
                旋转
              </button>
              <button @click="downloadCurrentPage" class="btn-tool" title="下载当前页">
                下载
              </button>
            </div>
          </div>
          <!-- 主预览区域 -->
          <div class="canvas-container" ref="canvasContainer">
            <div class="image-wrapper" :style="imageStyle">
              <!-- 当前页面处理中 -->
              <div v-if="currentPageStatus === 'processing'" class="main-processing-placeholder">
                <div class="main-processing-content">
                  <div class="main-processing-spinner"></div>
                  <p>第 {{ currentPage }} 页正在处理中...</p>
                </div>
              </div>
              <!-- 当前页面加载失败 -->
              <div v-else-if="currentPageStatus === 'error'" class="main-error-placeholder">
                <div class="main-error-content">
                  <div class="main-error-icon">⚠️</div>
                  <p>第 {{ currentPage }} 页加载失败</p>
                  <button class="main-retry-btn" @click="retryLoadPage(currentPage - 1)">重试</button>
                </div>
              </div>
              <!-- 正常显示图片 -->
              <img
                  v-else-if="currentPageUrl && currentPageStatus === 'loaded'"
                  :src="getMainImageUrl()"
                  class="pdf-image"
                  alt="PDF page"
                  @load="handleImageLoad"
                  @error="handleMainImageError"
              />
              <!-- 默认占位符 -->
              <div v-else class="no-image-placeholder">
                <div class="placeholder-content">
                  <i class="placeholder-icon">📄</i>
                  <p>页面加载中...</p>
                </div>
              </div>
            </div>
          </div>
          <!-- 旋转操作提示 -->
          <div v-if="hasUnsavedRotations" class="rotation-notice">
            <div class="notice-content">
              <span class="notice-icon">⚠️</span>
              <span class="notice-text">您有 {{ rotatedPagesCount }} 页进行了旋转，请在表单中点击"更新"按钮保存更改</span>
              <button @click="resetAllRotations" class="reset-all-btn">重置所有旋转</button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 下侧上传区域 -->
    <div v-else class="upload-container"
         :class="{ 'drag-over-highlight': isDraggingOver }">
      <div class="upload-content">
        <el-upload
            class="upload-demo"
            :auto-upload="false"
            :on-change="handleFileSelect"
            :on-remove="handleFileRemove"
            drag
            multiple
            :file-list="fileList"
            :show-file-list="false"
        >
          <div class="upload-inner">
            <i class="el-icon-upload"></i>
            <span class="upload-text">点击或将文件拖拽到这里上传</span>
            <span class="upload-hint">类型支持 .PDF .JPG .PNG</span>
          </div>
        </el-upload>
      </div>
    </div>
    <!-- 加载动画 -->
    <div v-if="loading" class="loading-overlay">
      <div class="loading-spinner">
        <div class="spinner"></div>
        <div class="spinner-text">{{ loadingText }}</div>
        <div v-if="uploadProgress > 0" class="upload-progress">
          <div class="progress-bar">
            <div class="progress-fill" :style="{ width: `${uploadProgress}%` }"></div>
          </div>
          <div class="progress-text">{{ uploadProgress }}%</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, watch, onMounted, nextTick, onBeforeUnmount, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessageBox, ElMessage } from 'element-plus'
import {
  appendFile,
  getFileSize,
  uploadPdfOrImage,
  getPdfImageUrls,
  updatePdfPageOrder,
  updatePdfPage
} from "@/api/Manage/File.js"
import { deletePdfPage } from "@/api/Manage/paper.js"

const MAX_FILE_SIZE = 100 * 1024 * 1024 // 100MB
const THUMBNAIL_BUFFER = 3 // 缩略图懒加载缓冲区大小

const router = useRouter()
const scale = ref(0.7)
const fileInput = ref(null)
const currentPage = ref(1)
const totalPages = ref(0)
const showThumbnails = ref(true)
const canvasContainer = ref(null)
const thumbnailList = ref(null)

// 拖拽状态变量
const isDraggingOver = ref(false)
const dragLeaveTimeout = ref(null)

// 文件信息
const currentFileInfo = ref(null)

// 懒加载相关
const visibleThumbnailRange = ref({ start: 0, end: 5 })
const thumbnailObserver = ref(null)

// URL缓存 - 避免重复生成
const urlCache = ref(new Map())
const mainImageUrlCache = ref('')

const props = defineProps({
  pdfUrl: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['update:pdf-path', 'rotations-changed'])

const pages = ref([])
const ruleForm = reactive({
  pdfPath: ''
})

const loadingText = ref('')
const fileList = ref([])
const showPreview = ref(false)
const loading = ref(false)
const uploadProgress = ref(0)

// 为每个页面单独存储旋转角度（仅前端显示，不立即保存）
const pageRotations = ref([])

// 处理中的页面数量
const processingPages = computed(() => {
  return pages.value.filter(page => page.status === 'processing').length
})

// 当前页面的URL
const currentPageUrl = computed(() => {
  if (pages.value.length === 0 || currentPage.value <= 0 || currentPage.value > pages.value.length) {
    return null
  }
  return pages.value[currentPage.value - 1]?.url
})

// 当前页面状态
const currentPageStatus = computed(() => {
  if (pages.value.length === 0 || currentPage.value <= 0 || currentPage.value > pages.value.length) {
    return 'loading'
  }
  return pages.value[currentPage.value - 1]?.status || 'loading'
})

// 图片样式，包括缩放和旋转
const imageStyle = computed(() => {
  const rotation = pageRotations.value[currentPage.value - 1] || 0
  return {
    transform: `scale(${scale.value}) rotate(${rotation}deg)`,
    transformOrigin: 'center center'
  }
})

// 检查是否有未保存的旋转
const hasUnsavedRotations = computed(() => {
  return pageRotations.value.some(rotation => rotation !== 0)
})

// 计算旋转的页面数量
const rotatedPagesCount = computed(() => {
  return pageRotations.value.filter(rotation => rotation !== 0).length
})

// 检查当前页面是否有旋转
const hasCurrentPageRotation = computed(() => {
  return (pageRotations.value[currentPage.value - 1] || 0) !== 0
})

// 检查指定页面是否有旋转
const hasRotation = (index) => {
  return (pageRotations.value[index] || 0) !== 0
}

// 生成无缓存URL的函数
const generateNoCacheUrl = (url) => {
  if (!url) return url
  const randomParam = Math.random().toString(36).substring(2, 15)
  const timestamp = Date.now()
  const separator = url.includes('?') ? '&' : '?'
  return `${url}${separator}nocache=${timestamp}&rand=${randomParam}`
}

// 获取缩略图URL - 使用缓存避免重复生成
const getThumbnailUrl = (page, index) => {
  if (!page.url) return ''

  const cacheKey = `thumbnail-${index}-${page.url}-${pageRotations.value[index] || 0}`

  if (!urlCache.value.has(cacheKey)) {
    const noCacheUrl = generateNoCacheUrl(page.url)
    urlCache.value.set(cacheKey, noCacheUrl)
  }

  return urlCache.value.get(cacheKey)
}

// 获取主图片URL - 使用缓存
const getMainImageUrl = () => {
  if (!currentPageUrl.value) return ''

  const currentIndex = currentPage.value - 1
  const cacheKey = `main-${currentIndex}-${currentPageUrl.value}-${pageRotations.value[currentIndex] || 0}`

  if (mainImageUrlCache.value !== cacheKey) {
    mainImageUrlCache.value = generateNoCacheUrl(currentPageUrl.value)
  }

  return mainImageUrlCache.value
}

// 清除URL缓存
const clearUrlCache = () => {
  urlCache.value.clear()
  mainImageUrlCache.value = ''
}

// 旋转当前页面（仅前端显示）
const rotateCurrentPage = () => {
  if (currentPageStatus.value !== 'loaded') {
    ElMessage.warning('当前页面未加载完成，无法旋转')
    return
  }
  const currentIndex = currentPage.value - 1
  const currentRotation = pageRotations.value[currentIndex] || 0
  const newRotation = (currentRotation + 90) % 360

  // 使用Vue的响应式更新，避免直接修改数组
  const newRotations = [...pageRotations.value]
  newRotations[currentIndex] = newRotation
  pageRotations.value = newRotations

  // 清除相关缓存
  const thumbnailCacheKey = `thumbnail-${currentIndex}`
  const mainCacheKey = `main-${currentIndex}`

  // 删除相关的缓存项
  for (const [key] of urlCache.value) {
    if (key.startsWith(thumbnailCacheKey) || key.startsWith(mainCacheKey)) {
      urlCache.value.delete(key)
    }
  }
  mainImageUrlCache.value = ''

  console.log(`第 ${currentPage.value} 页旋转到 ${newRotation}°`)
  // 通知父组件旋转状态改变
  emitRotationsChanged()
}

// 重置当前页面旋转
const resetCurrentPageRotation = () => {
  const currentIndex = currentPage.value - 1
  const newRotations = [...pageRotations.value]
  newRotations[currentIndex] = 0
  pageRotations.value = newRotations

  // 清除相关缓存
  clearUrlCache()

  console.log(`第 ${currentPage.value} 页旋转已重置`)
  ElMessage.info(`第 ${currentPage.value} 页旋转已重置`)
  // 通知父组件旋转状态改变
  emitRotationsChanged()
}

// 重置所有旋转
const resetAllRotations = async () => {
  try {
    await ElMessageBox.confirm('确定要重置所有页面的旋转吗？', '确认重置', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    pageRotations.value = new Array(totalPages.value).fill(0)

    // 清除所有缓存
    clearUrlCache()

    ElMessage.success('所有页面旋转已重置')
    // 通知父组件旋转状态改变
    emitRotationsChanged()
  } catch {
    // 用户取消操作
  }
}

// 通知父组件旋转状态改变
const emitRotationsChanged = () => {
  const rotations = pageRotations.value.map((rotation, index) => ({
    pageIndex: index,
    rotation: rotation
  })).filter(item => item.rotation !== 0)
  emit('rotations-changed', rotations)
}

// 提供给父组件调用的保存旋转方法
const saveRotations = async () => {
  const rotationsToSave = pageRotations.value
      .map((rotation, index) => ({ pageIndex: index, rotation }))
      .filter(item => item.rotation !== 0)

  if (rotationsToSave.length === 0) {
    return { success: true, message: '没有需要保存的旋转' }
  }

  try {
    loading.value = true
    loadingText.value = '正在保存旋转...'

    for (const { pageIndex, rotation } of rotationsToSave) {
      const pageNumber = pageIndex + 1
      console.log(`保存第 ${pageNumber} 页的旋转: ${rotation}°`)

      // 获取当前页面的图片URL
      const pageUrl = pages.value[pageIndex]?.url
      if (!pageUrl) {
        throw new Error(`第 ${pageNumber} 页的图片URL不存在`)
      }

      // 将旋转后的图片转换为File对象
      const rotatedFile = await rotateImageAndConvertToFile(pageUrl, rotation)

      // 调用后端接口更新页面
      const formData = new FormData()
      formData.append('filePath', ruleForm.pdfPath)
      formData.append('pageNumber', pageNumber.toString())
      formData.append('newFile', rotatedFile)

      const response = await updatePdfPage(formData)
      if (response.code !== '0') {
        throw new Error(`第 ${pageNumber} 页保存失败: ${response.message || '未知错误'}`)
      }
      console.log(`第 ${pageNumber} 页旋转保存成功`)
    }

    // 保存成功后重置旋转角度并重新加载
    pageRotations.value = new Array(totalPages.value).fill(0)
    clearUrlCache() // 清除缓存
    await reloadPDF(ruleForm.pdfPath)

    // 通知父组件旋转状态改变
    emitRotationsChanged()

    return {
      success: true,
      message: `成功保存 ${rotationsToSave.length} 页的旋转`
    }
  } catch (error) {
    console.error('保存旋转失败:', error)
    return {
      success: false,
      message: `保存旋转失败: ${error.message}`
    }
  } finally {
    loading.value = false
    loadingText.value = ''
  }
}

// 暴露方法给父组件
defineExpose({
  saveRotations,
  hasUnsavedRotations,
  rotatedPagesCount
})

// 检查URL是否有效
const isValidUrl = (url) => {
  if (!url || typeof url !== 'string') {
    return false
  }
  try {
    new URL(url)
    return true
  } catch {
    return false
  }
}

// 改进的图片加载函数，支持重试和更好的错误处理（无缓存版本）
const loadImageWithRetry = (url, maxRetries = 3) => {
  return new Promise((resolve, reject) => {
    let retryCount = 0
    const attemptLoad = () => {
      const img = new Image()
      // 设置跨域属性
      img.crossOrigin = 'anonymous'

      img.onload = () => {
        console.log(`图片加载成功: ${url}`)
        resolve(img)
      }

      img.onerror = (error) => {
        retryCount++
        console.error(`图片加载失败 (尝试 ${retryCount}/${maxRetries}): ${url}`, error)
        if (retryCount < maxRetries) {
          console.log(`正在重试加载图片... (${retryCount + 1}/${maxRetries})`)
          // 延迟重试
          setTimeout(() => {
            attemptLoad()
          }, 1000 * retryCount) // 递增延迟
        } else {
          reject(new Error(`图片加载失败，已重试 ${maxRetries} 次。URL: ${url}`))
        }
      }

      // 使用无缓存URL
      const noCacheUrl = generateNoCacheUrl(url)
      console.log(`尝试加载图片: ${noCacheUrl}`)
      img.src = noCacheUrl
    }
    attemptLoad()
  })
}

// 改进的图片旋转函数
const rotateImageAndConvertToFile = async (imageUrl, rotationAngle) => {
  try {
    console.log(`开始旋转图片: ${imageUrl}, 角度: ${rotationAngle}`)

    // 验证URL
    if (!isValidUrl(imageUrl)) {
      throw new Error(`无效的图片URL: ${imageUrl}`)
    }

    // 使用改进的图片加载函数
    const img = await loadImageWithRetry(imageUrl)
    console.log(`图片加载成功，尺寸: ${img.width}x${img.height}`)

    return new Promise((resolve, reject) => {
      try {
        const canvas = document.createElement('canvas')
        const ctx = canvas.getContext('2d')
        if (!ctx) {
          throw new Error('无法获取Canvas上下文')
        }

        // 根据旋转角度设置canvas尺寸
        if (rotationAngle % 180 === 0) {
          canvas.width = img.width
          canvas.height = img.height
        } else {
          canvas.width = img.height
          canvas.height = img.width
        }

        console.log(`Canvas尺寸设置为: ${canvas.width}x${canvas.height}`)

        // 移动到canvas中心
        ctx.translate(canvas.width / 2, canvas.height / 2)
        // 旋转
        ctx.rotate((rotationAngle * Math.PI) / 180)
        // 绘制图片（从中心开始）
        ctx.drawImage(img, -img.width / 2, -img.height / 2)

        console.log('图片绘制完成，开始转换为Blob')

        // 转换为Blob
        canvas.toBlob((blob) => {
          if (blob) {
            const file = new File([blob], `rotated-page-${Date.now()}.jpg`, {
              type: 'image/jpeg',
              lastModified: Date.now()
            })
            console.log(`文件转换成功，大小: ${(blob.size / 1024).toFixed(2)}KB`)
            resolve(file)
          } else {
            reject(new Error('Canvas转换为Blob失败'))
          }
        }, 'image/jpeg', 0.9)
      } catch (error) {
        console.error('Canvas处理过程中出错:', error)
        reject(error)
      }
    })
  } catch (error) {
    console.error('图片旋转过程中出错:', error)
    throw error
  }
}

// 判断是否应该加载缩略图
const shouldLoadThumbnail = (index) => {
  return index >= visibleThumbnailRange.value.start &&
      index <= visibleThumbnailRange.value.end
}

// 处理缩略图滚动
const handleThumbnailScroll = () => {
  if (!thumbnailList.value) return

  const container = thumbnailList.value
  const itemHeight = 140 // 缩略图项目高度
  const containerHeight = container.clientHeight
  const scrollTop = container.scrollTop

  const start = Math.max(0, Math.floor(scrollTop / itemHeight) - THUMBNAIL_BUFFER)
  const end = Math.min(pages.value.length - 1,
      Math.floor((scrollTop + containerHeight) / itemHeight) + THUMBNAIL_BUFFER)

  visibleThumbnailRange.value = { start, end }

  // 预加载可见范围内的缩略图
  for (let i = start; i <= end; i++) {
    if (pages.value[i] && pages.value[i].status === 'pending') {
      loadPageImage(i)
    }
  }
}

// 加载单个页面图片
const loadPageImage = async (index) => {
  if (!pages.value[index] || pages.value[index].status !== 'pending') {
    return
  }

  pages.value[index].status = 'loading'
  try {
    // 这里可以添加图片预加载逻辑
    // 由于图片URL已经生成，直接标记为loaded
    pages.value[index].status = 'loaded'
  } catch (error) {
    console.error(`页面 ${index + 1} 加载失败:`, error)
    pages.value[index].status = 'error'
  }
}

// 重试加载页面
const retryLoadPage = async (index) => {
  if (pages.value[index]) {
    pages.value[index].status = 'pending'
    await loadPageImage(index)
  }
}

// 处理图片加载完成事件
const handleImageLoad = (event) => {
  console.log('主图片加载成功')
}

// 处理缩略图加载完成事件
const handleThumbnailLoad = (index) => {
  console.log(`缩略图 ${index + 1} 加载成功`)
  if (pages.value[index]) {
    pages.value[index].status = 'loaded'
  }
}

// 处理主图片加载错误
const handleMainImageError = (event) => {
  console.error('主图片加载失败:', event.target.src)
  if (event.target.dataset.errorHandled) {
    return
  }
  event.target.dataset.errorHandled = 'true'

  // 更新当前页面状态
  const pageIndex = currentPage.value - 1
  if (pages.value[pageIndex]) {
    pages.value[pageIndex].status = 'error'
  }
  ElMessage.error(`第 ${currentPage.value} 页图片加载失败`)
  event.target.style.display = 'none'
}

// 处理缩略图加载错误
const handleImageError = (event, index) => {
  console.error(`缩略图 ${index + 1} 加载失败:`, event.target.src)
  if (event.target.dataset.errorHandled) {
    return
  }
  event.target.dataset.errorHandled = 'true'

  // 更新页面状态
  if (pages.value[index]) {
    pages.value[index].status = 'error'
  }
  event.target.style.display = 'none'
}

// 下载当前页面
const downloadCurrentPage = () => {
  if (currentPageUrl.value) {
    const link = document.createElement('a')
    link.href = generateNoCacheUrl(currentPageUrl.value)
    link.download = `page-${currentPage.value}.jpg`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    ElMessage.success(`第 ${currentPage.value} 页下载成功`)
  }
}

const formatDate = (date) => {
  if (!date) return ''
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

//添加文件按钮
const triggerFileInput = () => {
  if (fileInput.value) {
    fileInput.value.click()
  }
}

// 处理拖拽离开事件
const handleDragLeave = (event) => {
  const relatedTarget = event.relatedTarget
  if (relatedTarget && event.currentTarget.contains(relatedTarget)) {
    return
  }
  if (dragLeaveTimeout.value) {
    clearTimeout(dragLeaveTimeout.value)
  }
  dragLeaveTimeout.value = setTimeout(() => {
    isDraggingOver.value = false
  }, 100)
}

// 处理文件拖放功能
const handleFileDrop = async (event) => {
  isDraggingOver.value = false
  const files = event.dataTransfer.files
  if (files.length === 0) return

  if (showPreview.value && ruleForm.pdfPath) {
    // 已有PDF打开，追加文件
    for (let i = 0; i < files.length; i++) {
      const file = files[i]
      await appendFileToExistingPdf(file)
    }
  } else {
    // 没有PDF打开，上传新文件
    handleUpload(files[0])
  }
}

// 追加文件到现有PDF的方法
const appendFileToExistingPdf = async (file) => {
  const fileType = file.type
  const allowedTypes = ['application/pdf', 'image/jpeg', 'image/jpg', 'image/png']

  if (!allowedTypes.includes(fileType)) {
    ElMessage.error(`不支持的文件类型：${file.name}。仅支持 PDF、JPG 和 PNG 文件。`)
    return
  }

  if (file.size > MAX_FILE_SIZE) {
    ElMessage.error(`文件大小不能超过100MB。当前文件大小：${(file.size / 1024 / 1024).toFixed(2)}MB`)
    return
  }

  try {
    loading.value = true
    loadingText.value = '正在添加页面...'

    const formData = new FormData()
    formData.append('filePath', ruleForm.pdfPath)
    formData.append('fileToAppend', file)

    const response = await appendFile(formData)
    ElMessage.success('页面添加成功')

    // 清除缓存后重新加载
    clearUrlCache()
    await reloadPDF(ruleForm.pdfPath)
  } catch (error) {
    console.error("追加文件失败", error)
    ElMessage.error("页面添加失败，请重试")
  } finally {
    loading.value = false
  }
}

// 追加上传文件方法
const handleFileChange = async (event) => {
  const files = event.target.files
  if (files.length > 0) {
    const file = files[0]
    await appendFileToExistingPdf(file)
    event.target.value = ''
  }
}

// 获取当前文件大小的函数
const getCurrentFileSize = async (filePath) => {
  try {
    const size = await getFileSize(filePath)
    return size
  } catch (error) {
    console.error("获取文件大小失败", error)
    ElMessage.error("获取文件大小失败，请重试")
    return 0
  }
}

const loadPdf = async () => {
  try {
    if (!props.pdfUrl) {
      console.warn('PDF URL为空，跳过加载')
      return
    }

    console.log('开始加载PDF:', props.pdfUrl)
    loading.value = true
    loadingText.value = '正在加载PDF...'

    // 重置预览状态
    resetPreview()

    // 设置文件路径
    ruleForm.pdfPath = props.pdfUrl
    currentFileInfo.value = { imageBasePath: props.pdfUrl }

    // 显示预览区域
    showPreview.value = true
    await nextTick()

    // 加载PDF图片
    await loadPdfImages({ imageBasePath: props.pdfUrl })
    console.log('PDF加载完成')
  } catch (error) {
    console.error('PDF加载失败:', error)
    ElMessage.error(`PDF加载失败: ${error.message}`)
    resetPreview()
  } finally {
    loading.value = false
    loadingText.value = ''
  }
}

// 重新加载PDF的函数
const reloadPDF = async (pdfPath) => {
  try {
    loading.value = true
    loadingText.value = '正在重新加载PDF...'

    showPreview.value = true
    await nextTick()

    // 如果pdfPath是字符串，需要转换为对象格式
    let fileInfo
    if (typeof pdfPath === 'string') {
      fileInfo = { imageBasePath: pdfPath }
    } else {
      fileInfo = pdfPath
    }

    await loadPdfImages(fileInfo)
  } catch (error) {
    console.error('PDF重新加载失败:', error)
    ElMessage.error('PDF重新加载失败，请重试')
    resetPreview()
  } finally {
    loading.value = false
    loadingText.value = ''
  }
}

// Element Plus 上传组件的文件选择处理
const handleFileSelect = async (file, fileList) => {
  console.log('文件选择:', file, fileList)

  // 验证文件类型
  const allowedTypes = ['application/pdf', 'image/jpeg', 'image/jpg', 'image/png']
  if (!allowedTypes.includes(file.raw.type)) {
    ElMessage.error(`不支持的文件类型：${file.name}。仅支持 PDF、JPG 和 PNG 文件。`)
    return
  }

  // 验证文件大小
  if (file.raw.size > MAX_FILE_SIZE) {
    ElMessage.error(`文件大小不能超过100MB。当前文件大小：${(file.raw.size / 1024 / 1024).toFixed(2)}MB`)
    return
  }

  // 开始上传
  await handleUpload(file.raw)
}

// 处理文件移除
const handleFileRemove = (file, fileList) => {
  console.log('文件移除:', file, fileList)
}

// 边上传边预览的核心函数
const handleUploadWithPreview = async (file) => {
  try {
    loading.value = true
    loadingText.value = '正在上传文件...'
    uploadProgress.value = 0

    // 立即显示预览界面
    showPreview.value = true
    await nextTick()

    // 如果是PDF，先预估页数并创建占位符
    if (file.type === 'application/pdf') {
      // 这里可以添加PDF页数预估逻辑
      // 暂时创建一些占位符页面
      const estimatedPages = 5 // 预估页数，实际应该通过文件分析获得
      initializePagesWithPlaceholders(estimatedPages)
    } else {
      // 图片文件，只有一页
      initializePagesWithPlaceholders(1)
    }

    const formData = new FormData()
    formData.append('file', file)

    // 模拟上传进度
    const progressInterval = setInterval(() => {
      if (uploadProgress.value < 90) {
        uploadProgress.value += Math.random() * 10
        loadingText.value = `上传中... ${Math.round(uploadProgress.value)}%`
      }
    }, 200)

    const response = await uploadPdfOrImage(formData)
    clearInterval(progressInterval)
    uploadProgress.value = 100

    if (response.code !== "0") {
      throw new Error('文件上传失败: ' + response.message)
    }

    ElMessage.success('文件上传成功，正在处理...')

    // 开始渐进式加载页面
    await handleProgressiveLoad(response.data)
  } catch (error) {
    console.error('文件上传失败:', error)
    ElMessage.error('文件上传失败: ' + (error.message || '未知错误'))
    uploadProgress.value = 0
    resetPreview()
  } finally {
    loading.value = false
    loadingText.value = ''
    uploadProgress.value = 0
  }
}

// 初始化页面占位符
const initializePagesWithPlaceholders = (pageCount) => {
  totalPages.value = pageCount
  currentPage.value = 1
  pages.value = Array.from({ length: pageCount }, (_, index) => ({
    url: '',
    index: index + 1,
    status: 'processing' // processing, loaded, error, pending
  }))
  pageRotations.value = new Array(pageCount).fill(0)

  // 清除缓存
  clearUrlCache()
}

// 渐进式加载页面
const handleProgressiveLoad = async (fileInfo) => {
  try {
    console.log('开始渐进式加载，文件信息:', fileInfo)

    // 保存文件信息
    currentFileInfo.value = fileInfo
    ruleForm.pdfPath = fileInfo.imageBasePath

    // 获取实际的图片URL列表
    const imageBasePath = fileInfo.imageBasePath
    const encodedFilePath = encodeURIComponent(imageBasePath)
    const response = await getPdfImageUrls(encodedFilePath)

    if (!response || response.code !== '0') {
      throw new Error(`接口返回错误：${response?.message || '未知错误'}`)
    }

    const { imageUrls, pageCount } = response.data

    // 更新实际页数
    totalPages.value = pageCount

    // 更新页面数据
    pages.value = imageUrls.map((url, index) => ({
      url: url,
      index: index + 1,
      status: index === 0 ? 'loaded' : 'pending' // 第一页立即加载，其他页面待加载
    }))

    pageRotations.value = new Array(pageCount).fill(0)

    // 优先加载当前页面和附近页面
    await loadPriorityPages()

    ElMessage.success(`成功加载 ${pageCount} 页内容`)
    emit('update:pdf-path', fileInfo)
  } catch (error) {
    console.error('渐进式加载失败:', error)
    ElMessage.error(`加载失败: ${error.message}`)
    resetPreview()
  }
}

// 优先加载重要页面
const loadPriorityPages = async () => {
  // 优先加载当前页面
  const currentIndex = currentPage.value - 1
  if (pages.value[currentIndex] && pages.value[currentIndex].status === 'pending') {
    await loadPageImage(currentIndex)
  }

  // 加载当前页面前后的页面
  const priorityIndexes = [
    currentIndex - 1,
    currentIndex + 1,
    currentIndex - 2,
    currentIndex + 2
  ].filter(index => index >= 0 && index < pages.value.length)

  for (const index of priorityIndexes) {
    if (pages.value[index] && pages.value[index].status === 'pending') {
      await loadPageImage(index)
      // 添加小延迟，避免同时加载太多图片
      await new Promise(resolve => setTimeout(resolve, 100))
    }
  }
}

// 加载PDF图片的函数 - 兼容原有逻辑
const loadPdfImages = async (fileInfo) => {
  try {
    console.log('开始加载PDF图片，参数:', fileInfo)

    // 参数验证和处理
    let imageBasePath
    if (typeof fileInfo === 'string') {
      imageBasePath = fileInfo
    } else if (typeof fileInfo === 'object' && fileInfo.imageBasePath) {
      imageBasePath = fileInfo.imageBasePath
    } else {
      throw new Error('参数格式错误，需要字符串路径或包含imageBasePath属性的对象')
    }

    console.log('处理后的图片基础路径:', imageBasePath)

    loading.value = true
    loadingText.value = '正在加载PDF图片...'
    resetPreview()

    const encodedFilePath = encodeURIComponent(imageBasePath)
    console.log('编码后的路径:', encodedFilePath)

    const response = await getPdfImageUrls(encodedFilePath)
    console.log('获取图片URL列表响应:', response)

    if (!response || response.code !== '0') {
      throw new Error(`接口返回错误：${response?.message || '未知错误'}`)
    }

    if (!response.data) {
      throw new Error('接口返回数据为空')
    }

    const { imageUrls, pageCount } = response.data

    if (!Array.isArray(imageUrls)) {
      throw new Error('接口返回的imageUrls不是数组格式')
    }

    if (typeof pageCount !== 'number' || pageCount <= 0) {
      throw new Error('接口返回的pageCount格式不正确')
    }

    console.log(`成功获取 ${pageCount} 页图片URL`)
    console.log('图片URL列表:', imageUrls)

    // 初始化页面数据
    totalPages.value = pageCount
    currentPage.value = 1
    pages.value = imageUrls.map((url, index) => {
      console.log(`页面 ${index + 1} URL:`, url)
      return {
        url: url,
        index: index + 1,
        status: 'loaded' // 传统加载方式，直接标记为已加载
      }
    })

    pageRotations.value = new Array(pageCount).fill(0)

    await nextTick()
    showPreview.value = true

    ElMessage.success(`成功加载 ${pageCount} 页内容`)
    console.log('PDF图片加载完成')
  } catch (error) {
    console.error('PDF图片加载失败:', error)
    ElMessage.error(`PDF图片加载失败: ${error.message}`)
    resetPreview()
  } finally {
    loading.value = false
  }
}

// 修改 goToPage 函数
const goToPage = (pageNumber) => {
  if (pageNumber >= 1 && pageNumber <= totalPages.value) {
    currentPage.value = pageNumber

    // 清除主图片缓存，确保切换页面时重新生成URL
    mainImageUrlCache.value = ''

    // 当切换页面时，预加载附近页面
    const pageIndex = pageNumber - 1
    if (pages.value[pageIndex] && pages.value[pageIndex].status === 'pending') {
      loadPageImage(pageIndex)
    }

    // 预加载前后页面
    const adjacentIndexes = [pageIndex - 1, pageIndex + 1]
    adjacentIndexes.forEach(index => {
      if (index >= 0 && index < pages.value.length &&
          pages.value[index] && pages.value[index].status === 'pending') {
        loadPageImage(index)
      }
    })
  }
}

// 添加缩放功能
const zoomIn = () => {
  scale.value = Math.min(scale.value + 0.1, 3.0) // 最大放大到300%
}

const zoomOut = () => {
  scale.value = Math.max(scale.value - 0.1, 0.2) // 最小缩小到20%
}

// 添加页面导航函数
const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    goToPage(currentPage.value + 1)
  }
}

const prevPage = () => {
  if (currentPage.value > 1) {
    goToPage(currentPage.value - 1)
  }
}

// 删除页面
const deletePage = async (index) => {
  try {
    await ElMessageBox.confirm('确定要删除此页面吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await deletePdfPage(ruleForm.pdfPath, index + 1)
    pages.value.splice(index, 1)
    totalPages.value--
    pageRotations.value.splice(index, 1)

    if (currentPage.value > totalPages.value) {
      goToPage(totalPages.value)
    }

    // 清除缓存后重新加载
    clearUrlCache()
    await reloadPDF(ruleForm.pdfPath)
    ElMessage.success('页面删除成功')

    // 通知父组件旋转状态改变
    emitRotationsChanged()
  } catch (error) {
    if (error === 'cancel') {
      ElMessage.info('已取消删除操作')
    } else {
      console.error('删除页面失败:', error)
      ElMessage.error('删除页面失败，请重试')
    }
  }

  if (totalPages.value === 0) {
    resetPreview()
  }
}

// 重置预览状态的函数
const resetPreview = () => {
  showPreview.value = false
  currentPage.value = 1
  totalPages.value = 0
  pages.value = []
  pageRotations.value = []
  currentFileInfo.value = null

  // 清除缓存
  clearUrlCache()
}

// 文件上传处理函数 - 使用新的边上传边预览逻辑
const handleUpload = async (file) => {
  await handleUploadWithPreview(file)
}

// 处理上传成功 - 保留原有逻辑作为备用
const handleUploadSuccess = async (fileInfo) => {
  try {
    console.log('处理上传成功，文件信息:', fileInfo)
    loading.value = true
    loadingText.value = '正在加载文件...'

    // 保存文件信息
    currentFileInfo.value = fileInfo
    ruleForm.pdfPath = fileInfo.imageBasePath

    showPreview.value = true
    await nextTick()

    let retryCount = 0
    const maxRetries = 3

    while (retryCount < maxRetries) {
      try {
        await loadPdfImages(fileInfo)
        ElMessage.success({
          message: '文件处理完成，已成功加载',
          duration: 3000
        })
        emit('update:pdf-path', fileInfo)
        return
      } catch (pdfError) {
        console.error(`PDF加载失败 (尝试 ${retryCount + 1}/${maxRetries}):`, pdfError)
        if (retryCount < maxRetries - 1) {
          loadingText.value = `PDF加载失败，正在重试 (${retryCount + 1}/${maxRetries})...`
          retryCount++
          await new Promise(resolve => setTimeout(resolve, 2000))
        } else {
          ElMessage.error('PDF预览失败，请稍后重试')
          resetPreview()
          break
        }
      }
    }
  } catch (error) {
    console.error('文件处理失败:', error)
    ElMessage.error('文件处理失败，请重试')
    resetPreview()
  } finally {
    loading.value = false
    loadingText.value = ''
  }
}

// 检查网络状态
const isOnline = ref(navigator.onLine)
const checkNetworkStatus = () => {
  window.addEventListener('online', () => {
    isOnline.value = true
    ElMessage.success('网络已恢复连接')
  })

  window.addEventListener('offline', () => {
    isOnline.value = false
    ElMessage.warning('网络连接已断开')
  })
}

const handleResize = () => {
  console.log('Window resized')
}

// 拖拽相关变量和函数
const draggedItem = ref(null)
const draggedOverItem = ref(null)

const handleDragStart = (event, index) => {
  draggedItem.value = index
  event.dataTransfer.effectAllowed = 'move'
  event.dataTransfer.setData('text/plain', index)
}

const handleDragEnter = (event, index) => {
  if (index !== draggedItem.value) {
    draggedOverItem.value = index
  }
}

const handleDrop = async (event, index) => {
  event.preventDefault()
  const fromIndex = parseInt(event.dataTransfer.getData('text/plain'), 10)
  const toIndex = index

  if (fromIndex !== toIndex) {
    const newPages = [...pages.value]
    const [movedItem] = newPages.splice(fromIndex, 1)
    newPages.splice(toIndex, 0, movedItem)
    pages.value = newPages

    const newRotations = [...pageRotations.value]
    const [movedRotation] = newRotations.splice(fromIndex, 1)
    newRotations.splice(toIndex, 0, movedRotation)
    pageRotations.value = newRotations

    if (currentPage.value === fromIndex + 1) {
      currentPage.value = toIndex + 1
    } else if (fromIndex < toIndex && currentPage.value > fromIndex + 1 && currentPage.value <= toIndex + 1) {
      currentPage.value--
    } else if (fromIndex > toIndex && currentPage.value < fromIndex + 1 && currentPage.value >= toIndex + 1) {
      currentPage.value++
    }

    // 清除缓存
    clearUrlCache()

    try {
      await updatePdfPageOrder(ruleForm.pdfPath, newPages.map(page => page.index))
      ElMessage.success('页面顺序更新成功')
    } catch (error) {
      console.error('更新页面顺序失败:', error)
      ElMessage.error('更新页面顺序失败，请重试')
    }

    // 通知父组件旋转状态改变
    emitRotationsChanged()
  }

  draggedItem.value = null
  draggedOverItem.value = null
}

watch(
    () => props.pdfUrl,
    async (newUrl) => {
      if (newUrl) {
        await nextTick() // 保证 canvas DOM 已挂载
        await loadPdf()  // 加载预览
      }
    },
    { immediate: true } // ✅ 确保初次加载时也触发
)

onMounted(async () => {
  console.log('组件挂载，props.pdfUrl:', props.pdfUrl)
  if (props.pdfUrl) {
    ruleForm.pdfPath = props.pdfUrl
    await nextTick()
    await loadPdf()

    // 处理初始化时的URL参数
    if (typeof props.pdfUrl === 'object') {
      await loadPdfImages(props.pdfUrl)
    } else {
      await loadPdfImages({ imageBasePath: props.pdfUrl })
    }
  }

  checkNetworkStatus()
  window.addEventListener('resize', handleResize)
})

onBeforeUnmount(() => {
  if (dragLeaveTimeout.value) {
    clearTimeout(dragLeaveTimeout.value)
  }
  window.removeEventListener('resize', handleResize)

  // 清理缓存
  clearUrlCache()
})
</script>

<style scoped>
.btn-tool {
  padding: 0.5rem;
  border: none;
  background: transparent;
  border-radius: 4px;
  cursor: pointer;
  color: #4b5563;
  transition: background-color 0.2s;
  font-size: 14px;
}

.btn-tool:hover {
  background: #f3f4f6;
}

.btn-tool:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.btn-tool.has-rotation {
  background: #fef3c7;
  color: #92400e;
}

.btn-tool.reset-btn {
  background: #fee2e2;
  color: #dc2626;
}

.btn-tool.reset-btn:hover {
  background: #fecaca;
}

.header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: bold;
}

.thumbnail-sidebar {
  width: 160px;
  min-width: 160px;
  border-right: 1px solid #e5e7eb;
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
  height: 1400px;
  overflow: hidden;
}

.thumbnail-list {
  flex: 1;
  overflow-y: auto;
  padding: 0;
  display: flex;
  flex-direction: column;
  gap: 0;
}

.thumbnail-item {
  position: relative;
  cursor: move;
  border: 2px solid transparent;
  border-radius: 4px;
  transition: all 0.2s;
  margin: 0;
  padding: 0;
  user-select: none;
}

.thumbnail-item.active {
  border-color: #409EFF;
}

.thumbnail-item.drag-over {
  border: 2px dashed #409EFF;
}

.thumbnail-item.processing {
  border-color: #f39c12;
}

.thumbnail-item.error {
  border-color: #e74c3c;
}

.thumbnail-item.rotated {
  border-color: #f59e0b;
  background-color: #fef3c7;
}

.thumbnail-wrapper {
  position: relative;
  overflow: hidden;
  min-height: 120px;
}

.thumbnail-image {
  width: 100%;
  height: auto;
  border-radius: 4px;
  display: block;
  min-height: 120px;
  background-color: #f5f5f5;
  transition: transform 0.3s ease;
}

.rotation-indicator {
  position: absolute;
  top: 2px;
  left: 2px;
  z-index: 10;
}

.rotation-badge {
  background: #f59e0b;
  color: white;
  font-size: 10px;
  padding: 2px 4px;
  border-radius: 3px;
  font-weight: bold;
}

.delete-btn {
  position: absolute;
  top: 4px;
  right: 4px;
  padding: 4px 8px;
  background: rgba(0, 0, 0, 0.7);
  border: none;
  border-radius: 4px;
  color: white;
  opacity: 0;
  transition: opacity 0.2s;
  font-size: 12px;
  z-index: 10;
}

.thumbnail-wrapper:hover .delete-btn {
  opacity: 1;
}

.add-page-btn {
  width: 100%;
  padding: 0.5rem;
  background: #3b82f6;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background-color 0.2s;
}

.add-page-btn:hover {
  background: #2563eb;
}

.unsaved-info {
  color: #f59e0b;
  font-size: 12px;
  margin-left: 8px;
}

.rotation-notice {
  background: #fef3c7;
  border: 1px solid #f59e0b;
  border-radius: 8px;
  padding: 12px;
  margin-top: 16px;
}

.notice-content {
  display: flex;
  align-items: center;
  gap: 8px;
}

.notice-icon {
  font-size: 16px;
}

.notice-text {
  flex: 1;
  color: #92400e;
  font-size: 14px;
}

.reset-all-btn {
  background: #dc2626;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 4px 8px;
  font-size: 12px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.reset-all-btn:hover {
  background: #b91c1c;
}

/* 处理中状态样式 */
.processing-placeholder {
  width: 100%;
  height: 120px;
  background: #fff3cd;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  border: 1px solid #f39c12;
}

.processing-content {
  text-align: center;
  color: #856404;
}

.processing-spinner {
  width: 20px;
  height: 20px;
  border: 2px solid #f39c12;
  border-top: 2px solid transparent;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 8px;
}

.processing-text {
  font-size: 12px;
}

/* 错误状态样式 */
.error-placeholder {
  width: 100%;
  height: 120px;
  background: #f8d7da;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  border: 1px solid #e74c3c;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.error-content {
  text-align: center;
  color: #721c24;
}

.error-icon {
  font-size: 24px;
  margin-bottom: 4px;
}

.error-text {
  font-size: 12px;
  margin-bottom: 8px;
}

.retry-btn {
  padding: 2px 8px;
  background: #e74c3c;
  color: white;
  border: none;
  border-radius: 3px;
  font-size: 10px;
  cursor: pointer;
}

.retry-btn:hover {
  background: #c0392b;
}

/* 懒加载占位符样式 */
.lazy-placeholder {
  width: 100%;
  height: 120px;
  background: #f8f9fa;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  border: 1px dashed #dee2e6;
}

.lazy-content {
  text-align: center;
  color: #6c757d;
}

.lazy-icon {
  font-size: 24px;
  margin-bottom: 4px;
}

.lazy-text {
  font-size: 12px;
}

/* 主预览区域的状态样式 */
.main-processing-placeholder {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  width: 100%;
  background-color: #fff3cd;
  border: 2px dashed #f39c12;
  border-radius: 8px;
}

.main-processing-content {
  text-align: center;
  color: #856404;
}

.main-processing-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f39c12;
  border-top: 4px solid transparent;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 16px;
}

.main-error-placeholder {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  width: 100%;
  background-color: #f8d7da;
  border: 2px dashed #e74c3c;
  border-radius: 8px;
}

.main-error-content {
  text-align: center;
  color: #721c24;
}

.main-error-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.main-retry-btn {
  padding: 8px 16px;
  background: #e74c3c;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  margin-top: 16px;
}

.main-retry-btn:hover {
  background: #c0392b;
}

.processing-info {
  color: #f39c12;
  font-size: 12px;
  margin-left: 8px;
}

.pdf-container {
  width: 100%;
  max-width: 100%;
  overflow: hidden;
}

.preview-wrapper {
  width: 100%;
  max-width: 100%;
  overflow: hidden;
}

.preview-content {
  display: flex;
  width: 100%;
  max-width: 100%;
  gap: 20px;
}

.preview-main {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 16px;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 16px;
  background: #f9fafb;
  border-radius: 8px;
}

.toolbar-left,
.toolbar-right {
  display: flex;
  align-items: center;
  gap: 8px;
}

.canvas-container {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #f3f4f6;
  border-radius: 8px;
  padding: 16px;
  height: 700px;
  overflow: hidden;
}

.image-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  width: 100%;
  transition: transform 0.3s ease;
}

.pdf-image {
  max-height: 100%;
  max-width: 100%;
  object-fit: contain;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  border-radius: 4px;
}

.no-image-placeholder {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  width: 100%;
  background-color: #fafafa;
  border: 2px dashed #d1d5db;
  border-radius: 8px;
}

.placeholder-content {
  text-align: center;
  color: #6b7280;
}

.placeholder-icon {
  font-size: 48px;
  margin-bottom: 16px;
  display: block;
}

.upload-container {
  background-color: white;
  width: 68vw;
  height: 40vh;
  margin: auto;
}

.upload-content {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.upload-inner {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.upload-text {
  color: #595959;
}

.upload-hint {
  color: #919191;
  font-size: 0.8rem;
}

.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.loading-spinner {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}

.spinner {
  width: 50px;
  height: 50px;
  border: 5px solid #f3f3f3;
  border-top: 5px solid #3498db;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.spinner-text {
  color: #3498db;
  font-size: 14px;
  text-align: center;
}

.upload-progress {
  width: 200px;
  margin-top: 15px;
}

.progress-bar {
  width: 100%;
  height: 6px;
  background-color: #f3f3f3;
  border-radius: 3px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background-color: #3498db;
  transition: width 0.3s ease;
}

.progress-text {
  text-align: center;
  margin-top: 5px;
  font-size: 12px;
  color: #666;
}

.drag-over-highlight {
  border: 2px dashed #409EFF;
  background-color: rgba(64, 158, 255, 0.05);
}

/* 优化消息提示样式 */
.el-message {
  z-index: 9999 !important;
}

.el-message--success {
  background: #f0f9eb;
  border-color: #e1f3d8;
}

.el-message--error {
  background: #fef0f0;
  border-color: #fde2e2;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .preview-content {
    flex-direction: column;
  }

  .thumbnail-sidebar {
    width: 100%;
    height: 120px;
    border-right: none;
    border-bottom: 1px solid #e5e7eb;
  }

  .thumbnail-list {
    flex-direction: row;
    overflow-x: auto;
    overflow-y: hidden;
  }

  .thumbnail-item {
    min-width: 80px;
    margin-right: 8px;
  }

  .canvas-container {
    height: 500px;
  }

  .toolbar {
    flex-wrap: wrap;
    gap: 8px;
  }

  .toolbar-left,
  .toolbar-right {
    flex-wrap: wrap;
  }
}
</style>
